﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;
using yao.Entity;
using yao.Mvc;
using MySql.Data.MySqlClient;

namespace yao.website.Controllers
{
    /// <summary>
    /// 客户资金流水
    /// </summary>
    public class SalesOrderCapitalController : BaseController
    {
        public ActionResult Index(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            Customers customers = new Customers();
            using (IDbSession cn = OpenSession())
            {
                //查询客户的所属订单列表
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Customer);
                q.Selects.Add(Customer_.CustomerId);//
                q.Selects.Add(Customer_.CustomerNo);//客户编号
                q.Selects.Add(Customer_.CustomerName);//客户名称
                q.Selects.Add(Customer_.CompanyCode);//企业代码
                q.Selects.Add(Customer_.ContactName);//联系人
                q.Selects.Add(Customer_.Address);//地址
                q.Selects.Add(Customer_.ReceivableCapital);//应收款
                q.Selects.Add(Customer_.Employee.EmployeeName);//业务负责人
                q.Selects.Add(Customer_.FinanceRemark);//财务备注
                q.Wheres.Add(Customer_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.Wheres.Add(Customer_.ReceivableCapital.TGreaterThan(0));
                q.ReturnMatchedCount = true;
                q.PageSize = 20;
                q.PageIndex = pageIndex;
                customers.TotalCount = cn.SelectCollection(customers.Items, q);
            }
            return View(customers);
        }


        #region 收款

        private SalesOrders GetSalesOrders(IDbSession cn, long customerid)
        {
            //查询客户的所属订单列表
            QueryExpression q = new QueryExpression();
            q.EntityType = typeof(SalesOrder);
            q.Selects.Add(SalesOrder_.SalesOrderId);//销售单号
            q.Selects.Add(SalesOrder_.SalesOrderNo);//销售单号
            q.Selects.Add(SalesOrder_.CreateTime);//订单日期
            q.Selects.Add(SalesOrder_.ActualAmount);//订单金额
            q.Selects.Add(SalesOrder_.SettleedAmount);//已收款
            q.Selects.Add(SalesOrder_.UnSettleedAmount);//应收款
            q.Selects.Add(SalesOrder_.IsCompleted);//应收款
            q.Selects.Add(SalesOrder_.SettleStatusId);//应收款
            q.Wheres.Add(SalesOrder_.CustomerId.TEqual(customerid));
            SalesOrders salesOrders = new SalesOrders();
            cn.SelectCollection(salesOrders.Items, q);

            for (int i = 0; i < salesOrders.Items.Count; i++)
            {
                QueryExpression query = new QueryExpression();
                query.EntityType = typeof(SalesOrderCapital);
                query.Selects.Add(SalesOrderCapital_.SalesOrderCapitalId);
                query.Selects.Add(SalesOrderCapital_.SalesOrderId);
                query.Selects.Add(SalesOrderCapital_.CapitalTime);//收款时间
                query.Selects.Add(SalesOrderCapital_.Amount);//金额
                query.Selects.Add(SalesOrderCapital_.PaymentType.PaymentTypeName);//收款方式
                query.Selects.Add(SalesOrderCapital_.Remark);//备注
                query.Wheres.Add(SalesOrderCapital_.SalesOrderId.TEqual(salesOrders.Items[i].SalesOrderId));
                SalesOrderCapitals SalesOrderCapitals = new SalesOrderCapitals();
                cn.SelectCollection(SalesOrderCapitals.Items, query);
                salesOrders.Items[i].SalesOrderCapitals = SalesOrderCapitals;
            }
            return salesOrders;
        }

        public ActionResult Receivables(long customerid)
        {
            Customer customer = new Customer() { CustomerId = customerid };
            using (IDbSession cn = OpenSession())
            {
                //查询客户
                cn.Select(customer, Customer_.CustomerName, Customer_.CustomerNo);
                ViewBag.Title = "收款-" + customer.CustomerNo;
                ViewBag.CustomerName = customer.CustomerName;//客户名称
                ViewBag.CustomerId = customer.CustomerId;//客户Id
                return View(GetSalesOrders(cn,customerid));
            }
        }


        [HttpPost]
        public ActionResult Receivables()
        {
            long customerid;
            long.TryParse(Request.Form["CustomerId"], out customerid);
            Customer customer = new Customer() { CustomerId = customerid };
            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    //查询客户
                    cn.Select(customer, Customer_.CustomerName, Customer_.CustomerNo);
                    ViewBag.Title = "收款-" + customer.CustomerNo;
                    ViewBag.CustomerName = customer.CustomerName;//客户名称
                    ViewBag.CustomerId = customer.CustomerId;//客户Id



                    long SalesOrderCapitalCount;
                    if (long.TryParse(Request.Form["SalesOrderCapitalCount"], out SalesOrderCapitalCount))
                    {
                        #region 获取表单数据
                        SalesOrderCapitals salesOrderCapitals = new SalesOrderCapitals();
                        for (int i = 0; i < SalesOrderCapitalCount; i++)
                        {
                            DateTime capitalTime;
                            DateTime.TryParse(Request.Form["CapitalTime_" + i], out capitalTime);

                            decimal amount;
                            decimal.TryParse(Request.Form["Amount_" + i], out amount);

                            long paymentTypeId;
                            long.TryParse(Request.Form["PaymentTypeId_" + i], out paymentTypeId);

                            string remark = Request.Form["Remark_" + i];

                            long salesOrderId;
                            long.TryParse(Request.Form["SalesOrderId_" + i], out salesOrderId);

                            if (amount <= 0 || paymentTypeId <= 0 || capitalTime == null || salesOrderId <= 0)
                            {
                                continue;
                            }



                            SalesOrderCapital salesOrderCapital = new SalesOrderCapital
                            {
                                Amount = amount,
                                CapitalEmployeeId = CurrentEmployee.EmployeeId,
                                CapitalTime = capitalTime,
                                PaymentTypeId = paymentTypeId,
                                SalesOrderId = salesOrderId,
                                Remark = remark
                            };
                            salesOrderCapitals.Items.Add(salesOrderCapital);
                        }
                        #endregion

                        if (salesOrderCapitals.Items.Count < 0)
                        {
                            AddPageError("提交数据有误");
                            return View(GetSalesOrders(cn, customerid));
                        }

                        foreach (SalesOrderCapital salesOrderCapital in salesOrderCapitals.Items)
                        {
                            cn.Insert(salesOrderCapital);

                            #region 订单资金和结算状态
                            MySqlCommand cmd = new MySqlCommand("update SalesOrder set UnSettleedAmount=UnSettleedAmount+@UnSettleedAmount,SettleedAmount=SettleedAmount+@SettleedAmount,SettleStatusId=@SettleStatusId where SalesOrderId=@SalesOrderId");
                            cmd.Parameters.AddWithValue("@UnSettleedAmount", -salesOrderCapital.Amount);
                            cmd.Parameters.AddWithValue("@SettleedAmount", salesOrderCapital.Amount); 
                            cmd.Parameters.AddWithValue("@SettleStatusId", SettleStatus.SettleedPart);
                            cmd.Parameters.AddWithValue("@SalesOrderId", salesOrderCapital.SalesOrderId);
                            cn.ExecuteNonQuery(cmd);

                            SalesOrder salesOrder = new SalesOrder { SalesOrderId = salesOrderCapital.SalesOrderId };
                            cn.Select(salesOrder, SalesOrder_.IsCompleted, SalesOrder_.SettleStatusId, SalesOrder_.UnSettleedAmount);
                            if (salesOrder.UnSettleedAmount == 0)
                            {
                                salesOrder.IsCompleted = true;
                                salesOrder.SettleStatusId = SettleStatus.SettleedComplete;
                                cn.Update(salesOrder, SalesOrder_.IsCompleted, SalesOrder_.SettleStatusId);
                            }

                            #region 修改客户表
                            if (salesOrder.IsCompleted && salesOrder.SettleStatusId == SettleStatus.SettleedComplete)
                            {
                                MySqlCommand cmdCustomer = new MySqlCommand("update Customer set ReceivableCapital=ReceivableCapital+@ReceivableCapital,NotCompletedOrderCount=NotCompletedOrderCount+@NotCompletedOrderCount where CustomerId=@CustomerId");
                                cmdCustomer.Parameters.AddWithValue("@ReceivableCapital", -salesOrderCapital.Amount);
                                cmdCustomer.Parameters.AddWithValue("@NotCompletedOrderCount", -1);
                                cmdCustomer.Parameters.AddWithValue("@CustomerId", customer.CustomerId);
                                cn.ExecuteNonQuery(cmdCustomer);
                            }
                            else
                            {
                                MySqlCommand cmdCustomer = new MySqlCommand("update Customer set ReceivableCapital=ReceivableCapital+@ReceivableCapital where CustomerId=@CustomerId");
                                cmdCustomer.Parameters.AddWithValue("@ReceivableCapital", -salesOrderCapital.Amount);
                                cmdCustomer.Parameters.AddWithValue("@CustomerId", customer.CustomerId);
                                cn.ExecuteNonQuery(cmdCustomer);
                            }
                            #endregion

                            #endregion
                        }
                    }
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }
            return new IframeResult(Url.Action("Receivables", new { customerid = customer.CustomerId }), Url.Action("Index"));
        }
        #endregion
    }
}
